//
//  SWPhoneBindingViewController.swift
//  ChildStory
//
//  Created by linhan on 16/9/6.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWPhoneBindingViewController: SWBaseViewController,UITextFieldDelegate,SWAPIComponent
{
    private var _intervalID:String = ""
    private var _smsSendTime:Double = 0
    lazy private var _getCodeBtn:UIButton = UIButton(type:.system)
    
    lazy private var _telTextField:UITextField = UITextField()
    lazy private var _codeTextField:UITextField = UITextField()
    lazy private var _passwordTextField:UITextField = UITextField()
    lazy private var _regBtn:UIButton = UIButton(type:.system)
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }
    
    deinit
    {
        trace("DEINIT RegisterViewController")
    }
    
    //是否处于冷却中
    private var inWaiting:Bool
    {
        return (SW.Config.GetVerifyCodeCDTime - ((NSDate().timeIntervalSince1970 - _smsSendTime))) > 0
    }
    
    private func setup()
    {
        title = "绑定手机号"
        
        view.backgroundColor = UIColor.lightGray
        
        let TextFieldWidth:CGFloat = view.width * 0.587
        let TextFieldHeight:CGFloat = 37
        let TextFieldLeftMargin:CGFloat = (view.width - TextFieldWidth) * 0.5
        let ButtonHGrid:CGFloat = 15
        let PlaceholderColor:UIColor = UIColor(hex: "0xC2C2C2")
        let InputColor:UIColor = UIColor.white
        
        _telTextField.frame = CGRectMake(TextFieldLeftMargin, 90, TextFieldWidth, TextFieldHeight)
        //_telTextField.textInset = UIEdgeInsetsMake(0, 19, 0, 19)
        _telTextField.font = UIFont.systemFont(ofSize:13)
        _telTextField.textAlignment = .center
        _telTextField.keyboardType = .phonePad
        _telTextField.clearButtonMode = .whileEditing
        _telTextField.delegate = self
        _telTextField.backgroundColor = UIColor(white: 0.97, alpha: 1)
        _telTextField.attributedPlaceholder = NSMutableAttributedString(string: "输入手机号码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _telTextField.textColor = InputColor
        view.addSubview(_telTextField)
        
        let CodeButtonWidth:CGFloat = 90
        let CodeButtonHeight:CGFloat = 37
        _getCodeBtn.frame = CGRectMake(_telTextField.right - CodeButtonWidth, _telTextField.bottom + ButtonHGrid, CodeButtonWidth, CodeButtonHeight)
        _getCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize:12)
        _getCodeBtn.setTitleColor(UIColor.white, for: .normal)
        _getCodeBtn.addTarget(self, action: #selector(getCodeBtnTapped), for: .touchUpInside)
        getCodeButtonEnabled = true
        view.addSubview(_getCodeBtn)
        
        //验证码
        _codeTextField.frame = CGRectMake(TextFieldLeftMargin, _getCodeBtn.y, _getCodeBtn.x - 3 - TextFieldLeftMargin, TextFieldHeight)
        _codeTextField.font = UIFont.systemFont(ofSize:13)
        _codeTextField.textAlignment = .center
        _codeTextField.keyboardType = .phonePad
        _codeTextField.delegate = self
        _codeTextField.backgroundColor = UIColor(white: 0.97, alpha: 1)
        _codeTextField.attributedPlaceholder = NSMutableAttributedString(string: "输入验证码", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        _codeTextField.textColor = InputColor
        view.addSubview(_codeTextField)
        
        //注册
        _regBtn.setBackgroundImage(UIImage(named:"auth_btn_login")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 19, 0, 19), resizingMode: .stretch), for: .normal)
        _regBtn.setTitleColor(UIColor.white, for: .normal)
        _regBtn.titleLabel?.font = UIFont.systemFont(ofSize:14)
        _regBtn.setTitle("绑定", for: .normal)
        _regBtn.frame = CGRectMake(TextFieldLeftMargin, _codeTextField.bottom + ButtonHGrid, TextFieldWidth, 37)
        _regBtn.addTarget(self, action: #selector(regBtnTapped), for: .touchUpInside)
        view.addSubview(_regBtn)
    }
    
    private var getCodeButtonEnabled:Bool = false
        {
        didSet
        {
            if getCodeButtonEnabled != oldValue
            {
                let imageName:String = getCodeButtonEnabled ? "auth_btn_login" : "auth_img_bg_input"
                _getCodeBtn.setBackgroundImage(UIImage(named:imageName)?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 19, 0, 19), resizingMode: .stretch), for: .normal)
                if getCodeButtonEnabled
                {
                    _getCodeBtn.setTitle("获取验证码", for: .normal)
                }
            }
        }
    }
    
    //更新获取按钮上的文字
    private func updateGetCodeBtn()
    {
        //30秒内只能发送一次
        let time:Double = SW.Config.GetVerifyCodeCDTime - ((NSDate().timeIntervalSince1970 - _smsSendTime))
        
        if time > 1
        {
            _getCodeBtn.setTitle("\(Int(time))秒后获取", for: .normal)
            getCodeButtonEnabled = false
        }
        else
        {
            clearInterval(_intervalID)
            getCodeButtonEnabled = true
        }
        
    }
    
    //发送请求以获取验证码
    private func getVerifyCode(tel:String)
    {
        let askCheckCodeReq:SWVerifyCodeFetchReq = SWVerifyCodeFetchReq()
        askCheckCodeReq.phone = tel
        askCheckCodeReq.action = .PhoneBinding
        askCheckCodeReq.successCallback = {response,cache in
            SVProgressHUD.showSuccess(withStatus:"验证码已发送")
        }
        
        askCheckCodeReq.failCallback = {[weak self] error in
            if let strongSelf = self
            {
                //验证码发送失败，需重新发送
                strongSelf._smsSendTime = 0
                clearInterval(strongSelf._intervalID)
                strongSelf._getCodeBtn.setTitle("获取验证码", for: .normal)
                strongSelf.getCodeButtonEnabled = true
                self?.bindingFail(error)
            }
        }
        load(askCheckCodeReq)
    }
    
    //注册
    private func binding(phone:String, verify:String)
    {
        let req = SWPhoneBindingReq()
        req.phone = phone
        req.verifyCode = verify
        req.successCallback = {[weak self] response,cache in
            if let account = SWAccountManager.sharedManager().account
            {
                account.phone = phone
                SWAccountManager.sharedManager().update()
                //获取邀请情况
                self?.fetchInvitation()
            }
        }
        req.failCallback = {[weak self] error in
            self?._regBtn.isEnabled = true
            self?.bindingFail(error)
        }
        load(req)
    }
    
    private func bindingFail(_ error:NSError)
    {
        if error.code == SWErrorCode.REGISTER_BUT_MOBILE_EXIST || error.code == SWErrorCode.PHONE_BINDING_BUT_OCCUPY
        {
            SVProgressHUD.showError(withStatus:"该手机号已经绑定过，请更换其他手机号")
        }
        else if error.code == SWErrorCode.PHONE_BINDING_BUT_BINDED
        {
            SVProgressHUD.showError(withStatus:"只能绑定一个手机号码")
        }
        else if error.code == SWErrorCode.VERIFY_CODE_ERROR
        {
            SVProgressHUD.showError(withStatus:"验证码错误，返回重新获取")
        }
        else
        {
            SVProgressHUD.showError(withStatus:"绑定失败，稍后重试")
        }
    }
    
    //获取邀请信息
    private func fetchInvitation()
    {
        let req = SWInvitationFetchReq()
        req.successCallback = {[weak self] response,cache in
            if let invitationsRsp = (response as? SWInvitationFetchRsp)?.invitations
            {
                SVProgressHUD.dismiss()
                let invitations = invitationsRsp.flatMap({SWInvitation(invitation: $0)})
                if let invitation = invitations.valueAt(0)
                {
                    let viewController = SWInvitationHandleViewController(invitation: invitation)
                    viewController.forceSupplement = true
                    self?.navigationController?.pushViewController(viewController, animated: true)
                }
                else
                {
                    let viewController = SWChildAddViewController()
                    viewController.forceSupplement = true
                    self?.navigationController?.pushViewController(viewController, animated: true)
                }
            }
            else
            {
                self?.fetchInvitationFail(SWError.DataError)
            }
        }
        req.failCallback = {[weak self] error in
            self?.fetchInvitationFail(error)
        }
        load(req)
    }
    
    private var _fetchInvitationFailTimes:Int = 0
    private func fetchInvitationFail(_ error:NSError)
    {
        //失败次数超过3次，当做没有邀请信息，转到孩子添加页
        _fetchInvitationFailTimes += 1
        if _fetchInvitationFailTimes >= 3
        {
            let viewController = SWChildAddViewController()
            viewController.forceSupplement = true
            navigationController?.pushViewController(viewController, animated: true)
        }
        else
        {
            SVProgressHUD.showError(withStatus:"注册失败，稍后重试")
        }
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
    {
        var inputEnable:Bool = true
        if textField == _telTextField
        {
            //手机号限制只能输入20个以内的数字
            let MaxCount:Int = 20
            inputEnable = string == "" || ((textField.text?.length ?? 0) + string.length < MaxCount && Regex("^[\\d-]+$").test(string))
        }
        return inputEnable
    }
    
    //MARK ============================================================================================
    //==============================               Selector             ===============================
    //=================================================================================================
    
    
    @objc private func getCodeBtnTapped()
    {
        let tel:String = _telTextField.text ?? ""
        if tel == ""
        {
            SVProgressHUD.showError(withStatus:"输入手机号码")
            return
        }
        if inWaiting
        {
            return
        }
        _smsSendTime = NSDate().timeIntervalSince1970
        
        getVerifyCode(tel: tel)
        clearTimeout(self._intervalID)
        _intervalID = setInterval(1, closure: {
            
            self.updateGetCodeBtn()
            
        })
        updateGetCodeBtn()
    }
    
    @objc private func regBtnTapped()
    {
        guard let tel = _telTextField.text , tel != "" else
        {
            SVProgressHUD.showError(withStatus:"输入手机号码")
            return
        }
        guard let code = _codeTextField.text , code != "" else
        {
            SVProgressHUD.showError(withStatus:"输入验证码")
            return
        }
        binding(phone: tel, verify: code)
        SVProgressHUD.show(withStatus:"绑定中...")
        _regBtn.isEnabled = false
    }
    
    @objc private func popBtnTapped()
    {
        navigationController?.popViewController(animated:true)
    }
    
    //点击空白区域，内容下移
    @objc private func viewTapped()
    {
        view.endEditing(true)
    }
    
}
